﻿using System;
using System.CodeDom;
using System.CodeDom.Compiler;
using System.IO;
using System.Net;
using System.Reflection;
using System.Runtime.Serialization.Formatters.Binary;
using System.Text;
using System.Web.Services.Description;
using System.Xml.Serialization;

namespace Utility
{
    public class WebServiceHelper
    {
        private WebServiceHelper() { }

        public static WebServiceHelper Instance = new WebServiceHelper();

        private WebClient webClient = null;
        private ServiceDescription description = null;
        private ServiceDescriptionImporter importer = null;
        private CodeDomProvider provider = null;
        private CodeCompileUnit unit = null;

        private void InitWebService(string strWebService)
        {
            // 1. 使用 WebClient 下载 WSDL 信息。
            webClient = new WebClient();
            Stream stream = webClient.OpenRead(strWebService + "?WSDL");
            // 2. 创建和格式化 WSDL 文档。
            description = ServiceDescription.Read(stream);
            // 3. 创建客户端代理代理类。
            importer = new ServiceDescriptionImporter();

            importer.ProtocolName = "Soap"; // 指定访问协议。
            importer.Style = ServiceDescriptionImportStyle.Client; // 生成客户端代理。

            importer.CodeGenerationOptions = CodeGenerationOptions.GenerateProperties | CodeGenerationOptions.GenerateNewAsync;

            importer.AddServiceDescription(description, null, null); // 添加 WSDL 文档。

            // 4. 使用 CodeDom 编译客户端代理类。
            CodeNamespace nmspace = new CodeNamespace(); // 为代理类添加命名空间，缺省为全局空间。
            unit = new CodeCompileUnit();
            unit.Namespaces.Add(nmspace);

            ServiceDescriptionImportWarnings warning = importer.Import(nmspace, unit);
            provider = CodeDomProvider.CreateProvider("CSharp");
        }

        public object CallWebServiceMethod(string strWebService, string strMethod, string strNameSpace, object[] objParams)
        {
            try
            {
                InitWebService(strWebService);

                CompilerParameters parameter = new CompilerParameters();
                parameter.GenerateExecutable = false;
                parameter.GenerateInMemory = true;
                parameter.ReferencedAssemblies.Add("System.dll");
                parameter.ReferencedAssemblies.Add("System.XML.dll");
                parameter.ReferencedAssemblies.Add("System.Web.Services.dll");
                parameter.ReferencedAssemblies.Add("System.Data.dll");

                CompilerResults result = provider.CompileAssemblyFromDom(parameter, unit);

                // 5. 使用 Reflection 调用 WebService。
                if (true == result.Errors.HasErrors)
                {
                    System.Text.StringBuilder sb = new StringBuilder();
                    foreach (CompilerError ce in result.Errors)
                    {
                        sb.Append(ce.ToString());
                        sb.Append(System.Environment.NewLine);
                    }
                    throw new Exception(sb.ToString());
                }

                Assembly asm = result.CompiledAssembly;
                Type t = null;
                if (!string.IsNullOrEmpty(strNameSpace))
                    t = asm.GetType(strNameSpace); // 如果在前面为代理类添加了命名空间，此处需要将命名空间添加到类型前面。
                else
                    t = asm.GetType();

                object o = Activator.CreateInstance(t);
                MethodInfo method = t.GetMethod(strMethod);

                return method.Invoke(o, objParams);
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        public byte[] SerializeObject(object pObj)
        {
            if (pObj == null)
                return null;
            System.IO.MemoryStream memoryStream = new System.IO.MemoryStream();
            BinaryFormatter formatter = new BinaryFormatter();
            formatter.Serialize(memoryStream, pObj);
            memoryStream.Position = 0;
            byte[] read = new byte[memoryStream.Length];
            memoryStream.Read(read, 0, read.Length);
            memoryStream.Close();
            return read;
        }

        public object DeserializeObject(byte[] pBytes)
        {
            object newOjb = null;
            if (pBytes == null)
            {
                return newOjb;
            }

            System.IO.MemoryStream memoryStream = new System.IO.MemoryStream(pBytes);
            memoryStream.Position = 0;
            BinaryFormatter formatter = new BinaryFormatter();
            newOjb = formatter.Deserialize(memoryStream);
            memoryStream.Close();

            return newOjb;
        }
    }
}